package com.etc.service.impl.warning;

import com.etc.utils.JxlExcelUtil;
import com.etc.utils.PoiExcelUtil;
import com.etc.vo.warning.BizThresholdVo;
import com.etc.repository.warning.BizThresholdRepository;
import com.etc.result.CodeMessage;
import com.etc.result.ResultBean;
import com.etc.service.warning.IBizThresholdService;
import com.etc.entity.warning.BizThreshold;
import com.etc.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Main 预警阈值表的列清单业务实现层
 * @Author zsw
 * @Date 2019/12/3 16:25
 **/
@Slf4j
@Service
public class BizThresholdServiceImpl implements IBizThresholdService {

    @Autowired
    private BizThresholdRepository bizThresholdRepository;

    /**
     * 根据类型查询
     * */
    @Override
    public List<BizThreshold> selectByType(String type) {
        try {
            List<BizThreshold> byType = bizThresholdRepository.findByType(type);
            return byType;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据预警等级查询
     */
    @Override
    public List<BizThreshold> selectByLevel(String level) {
        try {
            List<BizThreshold> byType = bizThresholdRepository.findByLevel(level);
            return byType;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据位置查询
     */
    @Override
    public List<BizThreshold> selectBySensorPosition(String sensorPosition) {
        try {
            List<BizThreshold> byType = bizThresholdRepository.findBySensorPosition(sensorPosition);
            return byType;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新
     */
    @Override
    public BizThreshold update(BizThreshold bizThreshold) {
        try {
            return bizThresholdRepository.save(bizThreshold);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据id查询
     */
    @Override
    public ResultBean findById(String id) {
        try {
            Optional<BizThreshold> byId = bizThresholdRepository.findById(id);
            if (StringUtil.isNotNull(byId)) {
                return ResultBean.success(byId.get());
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.error(CodeMessage.FIND_DEFEATED.getCode(), CodeMessage.FIND_DEFEATED.getMassage());
        }
    }

    /**
     * 分页查询
     */
    @Override
    public ResultBean findCriteriaByType(BizThreshold bizThreshold, Integer pageNum, Integer pageSize) {

        //获取pageable 添加所查询的页数以及每页展示信息的数量
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

        Specification<BizThreshold> spec = new Specification<BizThreshold>() {
            @Override
            public Predicate toPredicate(Root<BizThreshold> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> pr = new ArrayList<>();
                if (StringUtil.isNotNull(bizThreshold)) {

                    if (StringUtil.isNotNull(bizThreshold.getLevel())) {
                        pr.add(criteriaBuilder.equal(root.get("level"), bizThreshold.getLevel()));
                    }
                    if (StringUtil.isNotNull(bizThreshold.getType())) {
                        pr.add(criteriaBuilder.equal(root.get("type"), bizThreshold.getType()));
                    }
                    if (StringUtil.isNotNull(bizThreshold.getSensorPosition())) {
                        pr.add(criteriaBuilder.equal(root.get("sensorPosition"), bizThreshold.getSensorPosition()));
                    }
                    return criteriaBuilder.and(pr.toArray(new Predicate[pr.size()]));
                }
                return null;
            }
        };

        try {
            //通过JPA查询到bizSensorConfig表中所有的数据
            Page<BizThreshold> bizThresholds = bizThresholdRepository.findAll(spec, pageable);
            //调用组装方法
            Page<BizThresholdVo> bizThresholdVos = entityAssemble(bizThresholds, pageable);
            return ResultBean.success(bizThresholdVos);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 生成Excel
     * */
    @Override
    public ResultBean downExcel(String type) {
        try {
            List<BizThreshold> bizThresholdRepositoryByType = bizThresholdRepository.findByType(type);
            return JxlExcelUtil.downExcel_threshold(bizThresholdRepositoryByType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.FIND_DEFEATED.getCode(), CodeMessage.FIND_DEFEATED.getMassage());
        }
    }

    /**
     * 上传Excel
     * */
    @Override
    public ResultBean toExcel(String filename, MultipartFile file) throws IOException {
        InputStream input = file.getInputStream();
        List<BizThreshold> bizThresholds = PoiExcelUtil.toLead_threshold(filename, input);
        try {
            bizThresholdRepository.saveAll(bizThresholds);
            return ResultBean.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.UPDATE_DEFEATED.getCode(), CodeMessage.UPDATE_DEFEATED.getMassage());
        }
    }


    /**
     * 返回组装
     */
    public static Page<BizThresholdVo> entityAssemble(Page<BizThreshold> bizThresholds, Pageable pageable) {

        //创建一个List容器
        List<BizThresholdVo> bizThresholdVos = new ArrayList<>();

        //循环遍历bizSensorConfigPage中的数据
        for (BizThreshold bizThreshold : bizThresholds) {
            BizThresholdVo bizThresholdVo = new BizThresholdVo();
            bizThresholdVo.setId(bizThreshold.getId());
            bizThresholdVo.setLevel(bizThreshold.getLevel());
            bizThresholdVo.setSensorPosition(bizThreshold.getSensorPosition());
            bizThresholdVo.setValue(bizThreshold.getValue());
            bizThresholdVo.setRatio(bizThreshold.getRatio());
            bizThresholdVo.setUpdateDate(bizThreshold.getUpdateDate());
            bizThresholdVos.add(bizThresholdVo);
        }
        //创建一个自定义的Page 参数(组装的容器bizSensorConfigs，分页的信息pageable，数据总数bizSensorConfigPage.getTotalElements())
        Page<BizThresholdVo> bizThresholdVoPage = new PageImpl<BizThresholdVo>(bizThresholdVos,
                pageable, bizThresholdVos.size());
        return bizThresholdVoPage;

    }

}
